<template>
  <home/>
  <div class="contents-detal">
    <div class="header">
      <el-button link class="count" @click="openInfomation">{{ textData.title }}</el-button>
      <div class="telsw">
        <div class="text">负责人：{{ textData.username }}</div>
        <div class="text">发布权限：学生</div>
        <div class="text">时间: {{ textData.createTime }}</div>
      </div>
      <el-divider border-style="dashed"/>
    </div>
    <div class="required">
      <div @click="commentsProject" style="margin-left: 1%">评论列表</div>
      <div style="margin-left: 10%">项目评分</div>
      <el-rate v-model="value" :max="10" :disabled="disSocre" @click="socre" show-score allow-half text-color="#ff9900"
               score-template="{value} 分"/>
      <el-button text style="margin-left: 10px" type="primary" @click="openProject(textData)">项目详情</el-button>
    </div>
    <div class="chat-header">
      <el-card :body-style="{ padding: '0px' }">
      <ul infinite-scroll-distance="1" class="infinite-list" style="overflow: auto">
        <div ref="chatList" class="execInfo">
          <div class="common-layout" v-for="(item, index) in ChatHistory" :key="index">
            <div style="display: flex;height: 85px;margin-top: 2px">
              <img :src="item.userImg"/>
              <div style="margin-left: 20px;width: 80%">
                <div style="color: red;font-size: 12px">{{ item.username }}
                  <el-icon v-if="item.buserId!==item.userId && item.buserId!==0">
                    <CaretRight/>
                    {{ item.buserId !== item.userId ? item.busername : '' }}
                  </el-icon>
                </div>
                <div class="comment-text">
                  {{ item.content }}
                </div>
                <div class="timess">
                  <div style="margin-top: -12px">{{ item.createTime }}</div>
                  <div style="display: flex;margin-top: -10px">
                    <el-button style="font-size: 12px" @click="Support(item,item.id)" link>
                      <el-icon>
                        <ChatLineRound/>
                      </el-icon>
                      {{ item.isReply === 0 ? "回复" : "回复中" }}
                    </el-button>
                    <div class="timessReply" style="margin-left: -6px" @click="Reply(item)">
                      <el-button link>
                        <img style="width: 12px;height: 12px;margin-top: -1px" v-if="item.isLiked===1" :src="isLikedSvg"
                             alt="">
                        <img style="width: 12px;height: 12px;margin-top: -1px" v-else :src="noLikedSvg" alt="">
                        <span v-if="item.support>0"
                              style="margin-top: 1px;font-size: 12px;margin-left: 10px">{{ item.support }}</span>
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="item.displayedChildrenCount > 0" class="common-layout"
                 v-for="(items, index) in item.children.slice(0, item.displayedChildrenCount)" :key="index">
              <div style="display: flex;height: 85px;margin-top: -10px;margin-left: 50px">
                <img :src="items.userImg"/>
                <div style="margin-left: 20px;width: 80%">
                  <div style="color: red;font-size: 12px">{{ items.username }}
                    <el-icon v-if="items.buserId!==items.userId && items.buserId!==0">
                      <CaretRight/>
                    </el-icon>
                    {{ items.buserId !== items.userId ? items.busername : '' }}
                  </div>
                  <div class="comment-text">
                    {{ items.content }}
                  </div>
                  <div class="timess">
                    <div style="margin-top: -10px">{{ items.createTime }}</div>
                    <div style="display: flex;margin-top: -10px">
                      <el-button style="font-size: 12px" @click="Support(items,items.parentId)" link>
                        <el-icon>
                          <ChatLineRound/>
                        </el-icon>
                        {{ items.isReply === 0 ? "回复" : "回复中" }}
                      </el-button>
                      <div class="timessReply" style="margin-left: -6px" @click="Reply(item)">
                        <el-button link>
                          <img style="width: 12px;height: 12px;margin-top: -1px" v-if="item.isLiked===1"
                               :src="isLikedSvg" alt="">
                          <img style="width: 12px;height: 12px;margin-top: -1px" v-else :src="noLikedSvg" alt="">
                          <span v-if="item.support>0"
                                style="margin-top: 1px;font-size: 12px;margin-left: 10px">{{ item.support }}</span>
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="item.children.length>0" style="width: 200px;font-size: 10px;margin-top: -15px;margin-left: 60px">
              <el-button v-if="item.displayedChildrenCount < item.children.length || item.displayedChildrenCount === 0"
                         @click="toggleChildren(item,0)" text type="info" size="small">展开更多 <i
                class="el-icon-arrow-down"></i></el-button>
              <el-button v-if="item.displayedChildrenCount !== 0" text @click="toggleChildren(item,1)" type="info"
                         size="small">收起 <i class="el-icon-arrow-up"></i></el-button>
            </div>
          </div>
        </div>
        <div class="userinfo" style="margin-top: 10px">
          <div v-if="isreply" style="border-radius: 10%">
            <el-input style="max-width: 440px"
                      v-model="content" disabled :placeholder="content"/>
          </div>
          <div>
            <el-input
              v-model="contentInfo"
              style="max-width: 500px"
              @change="handBangd"
              :placeholder=" isreply ? '回复@'+busername : '留下你的精彩评论'"
              class="input-with-select"
              :suffix-icon="Picture"
            >
              <template #append>
                <el-button type="primary" @click="handBangd">发送</el-button>
              </template>
            </el-input>
          </div>
        </div>
      </ul>
      </el-card>
    </div>
  </div>
</template>
<script setup>
import home from '../welcome/Home.vue'
import {useRoute} from 'vue-router'
import isLikedSvg from './image/isLikedSvg.svg'
import noLikedSvg from './image/noLikedSvg.svg'
import {ref} from "vue";
import {
  commendId, commentsProjectId,
  commentSupport, openProject, recommend
} from "../welcome/welcomeApi.js";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/pinia/stores/user";
import {reactive} from "vue";
import {CaretRight, ChatLineRound, Picture} from "@element-plus/icons-vue";
const isreply = ref(false)
const border = ref(false)
const disabled = ref(true)
const disSocre = ref(false)
const content = ref('')
const value = ref('')
const busername = ref('')
const textData = JSON.parse(localStorage.getItem("project"))
const userStore = useUserStore()
const userData = userStore.userInfo
const contentInfo = ref('')
const chatList = ref()
const form = reactive({
  projectId: '',
  content: '',
  userId: '',
  buserId: '',
  busername: '',
  buserImg: '',
  createTime: '',
  isLiked: '',
  isReply: '',
  support: '',
  userImg: '',
  username: '',
  parentId: ''
})
const tableData1 = ref([])
const ChatHistory = ref([])
const sendData = ref([])
// 初始化每个父评论项的 displayedChildrenCount 属性
const commentsProject = async () => {
  await commentsProjectId(textData.id).then(res => {
    ChatHistory.value = res.data.map(item => ({
      ...item,
      displayedChildrenCount: 0 // 初始状态不展开任何子评论
    }));
    tableData1.value = res.data

  }).catch(res => {
    console.error(res);
  })
}
commentsProject();

const toggleChildren = (item, type) => {
  if (type === 0) {
    if (item.displayedChildrenCount < item.children.length) {
      item.displayedChildrenCount += 4; // 每次点击展开显示5条评论
    } else {
      item.displayedChildrenCount = item.children.length; // 收起时重置为0
    }
  } else {
    item.displayedChildrenCount = 0; // 收起时重置为0
  }
}

const socre = async () => {
  if (disSocre.value === false) {
    form.projectId = textData.id;
    form.userId = userData.id;
    await recommend(form, value.value);
    disSocre.value = true;
  }
}

const commends = async () => {
  await commendId(textData.id, userData.id).then(res => {
    if (res.code === 0) {
      value.value = res.data;
      disSocre.value = true;
    }
  }).catch(res => {
    console.error(res);
  })
}
commends();

const ws = ref(null)

const ljie = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    return;
  }
  ws.value = new WebSocket(`ws://localhost:8082/hotelReviews/${userData.id}`);
  ws.value.onopen = (event) => {
    console.log("WebSocket connected:", event);
  };
  ws.value.onerror = (error) => {
    console.error("WebSocket error:", error);
  };
  ws.value.onclose = (event) => {
    console.log("WebSocket closed:", event);
  };
  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      // 根据 parentId 判断是添加到父评论还是作为新的父评论
      if (message.parentId === 0) {
        // 添加新的父评论
        ChatHistory.value.push({
          ...message,
          displayedChildrenCount: 0, // 初始状态不展开任何子评论
          children: [] // 确保有 children 属性
        });
        // 如果 `isRefresh` 匹配当前用户 id，则自动滚动到底部
        if (message.isRefresh === userData.id) {
          scrollBottom();
        }
      } else {
        // 找到对应的父评论并添加子评论
        const parentComment = ChatHistory.value.find(comment => comment.id === message.parentId);
        if (parentComment) {
          if (!parentComment.children) {
            parentComment.children = [];
          }
          parentComment.children.push(message);
          // 如果子评论数超过当前显示的子评论数，更新 displayedChildrenCount
          // 显示到底部时，会自动更新 displayedChildrenCount
          if (message.isRefresh === userData.id) {
            parentComment.displayedChildrenCount = parentComment.children.length;
          }
        }
      }
      ChatHistory.value.forEach(item => {
        item.isReply = 0;
        if (item.children) {
          item.children.forEach(child => (child.isReply = 0));
        }
      });

    } catch (error) {
      console.error("消息解析失败:", error);
    }
  };
}
ljie();

const handBangd = async () => {
  if (contentInfo.value.length > 0) {
    form.projectId = textData.id;
    form.content = contentInfo.value;
    form.userId = userData.id;
    form.buserId = userData.id;
    form.busername = userData.username;
    form.buserImg = userData.headUrl;
    form.isLiked = 0;
    form.isReply = 1;
    form.userImg = userData.headUrl;
    form.username = userData.username;
    form.busername = userData.username;
    form.parentId = 0;
    if (sendData.value.userId !== undefined) {
      form.buserId = sendData.value.userId;
      form.busername = sendData.value.username;
      form.buserImg = sendData.value.userImg;
      form.parentId = sendData.value.parentId;
    }
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify(form)); // 发送消息
      contentInfo.value = '';
      isreply.value = false;
      sendData.value = {}
    } else {
      console.error("WebSocket is not connected.");
    }
  } else {
    ElMessage.error("请输入评论");
  }
}


const Reply = async (data) => {
  let support = 0;
  if (data.isLiked === 0) {
    data.support += 1;
    data.isLiked = 1;
    await commentSupport(data.id, support = 1).then(res => {
    }).catch(res => {
      console.error(res);
    });
  } else {
    data.support -= 1;
    data.isLiked = 0;
    await commentSupport(data.id, support = 0).then(res => {
    }).catch(res => {
      console.error(res);
    });
  }
}

const Support = (data, id) => {
  // 先将 ChatHistory 中所有评论的 isReply 状态置为 false
  ChatHistory.value.forEach(item => {
    if (data.id !== item.id) {
      item.isReply = 0;
      if (item.children) {
        item.children.forEach(child => (child.isReply = 0));
      }
    }
  });
  if (data.isReply === 0) {
    sendData.value = data;
    sendData.value.parentId = id;
    isreply.value = true;
    content.value = '回复@' + data.username + ' ：' + data.content;
    busername.value = data.username;
    data.isReply += 1;
  } else {
    sendData.value = {};
    isreply.value = false;
    data.isReply -= 1;
  }
}

const openInfomation = () => {
  localStorage.setItem("cementData", JSON.stringify(textData))
  window.open('http://localhost:3333/#/cementDetails', '_blank');
}
const scrollBottom = () => {
  chatList.value.scrollTop = chatList.value.scrollHeight;
}

</script>
<style scoped>
.button-con {
  margin-left: 90%;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.contents-detal {
  width: 990px;
  height: 600px;
  margin: 0 auto;
  margin-top: 20px;
}

.common-layout img {
  margin-top: 3px;
  margin-right: -10px;
  margin-left: 10px;
  border-radius: 50%;
  width: 50px;
  height: 50px;
}

.timess {
  color: #909399;
  font-size: 12px;
  margin-top: -5px;
}

.timessReply {
  display: flex;
}

.timessReply:hover {
  color: red;
}

.timess img {
  width: 17px;
  height: 17px;
}

.count {
  margin-left: 48%;
  font-size: 23px;
}

.counts {
  display: flex;
  flex-wrap: wrap;
}

.telsw {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.telsw .text {
  color: #475669;
  opacity: 0.7;
  font-size: 15px;
  margin-left: 20px;
}

.required {
  width: 100%;
  height: 50px;
  background-color: transparent;
  display: flex;
  align-items: center;
  font-size: 18px;
}

.infinite-list {
  height: 650px;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list .infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  background: var(--el-color-primary-light-9);
  margin: 10px;
  color: var(--el-color-primary);
}

.infinite-list .infinite-list-item + .list-item {
  margin-top: 10px;
}

.chat-header {
  position: relative;
  width: 100%;
  height: 90%;
}

.el-badge__content {
  font-size: 16px;
}

.execInfo {
  width: 100%;
  height: 550px;
  font-size: 16px;
  line-height: 33px;
  color: #606266;
  overflow-y: auto;
}

.userinfo {
  margin-left: 20px;
  width: 90%;
  bottom: 10px;
}

.right-data {
  margin-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.comment-text {
  margin-top: -10px;
  font-size: 13px;
  max-width: 400px;
  word-wrap: break-word;
  line-height: 1.3;
}

</style>
